package com.zyf.workflow.work;

import com.zyf.workflow.node.Node;
import com.zyf.workflow.node.bean.NodeResultBean;
import com.zyf.workflow.work.bean.WorkResult;
import com.zyf.workflow.work.bean.WorkTypeEnum;

import java.util.Iterator;
import java.util.List;

public abstract class AbstractWork<T> implements Work {

    private List<Node<?>> nodes;

    private String workName;

    protected String nextWork;

    private T data;

    @Override
    public WorkResult dowWork() {
        WorkResult workResult = new WorkResult();
        workResult.setFlag(true);
        workResult.setNextWork(nextWork);
        Iterator<Node<?>> iterator = nodes.iterator();
        Object param = null;

        while (iterator.hasNext()) {
            Node currentNode = iterator.next();
            NodeResultBean resultBean = currentNode.doWork(param);
            if (resultBean.isFlag()) {
                param = resultBean.getData();
                if (WorkTypeEnum.DECISION.equals(getWorkType())) {
                    workResult.setNextWork((String) param);
                }
            } else {
                workResult.setFlag(false);
                workFail();
                break;
            }

        }


        return workResult;
    }

    public AbstractWork(T data, String workName) {
        this.data = data;
        this.nodes = initNodes(data);
        this.workName = workName;
    }

    @Override
    public String getWorkName() {
        return workName;
    }

    @Override
    public String getNextWork() {
        return nextWork;
    }


    @Override
    public void setNextWork(String nextWork) {
        this.nextWork = nextWork;

    }

    public abstract List<Node<?>> initNodes(T data);

}
